import axios from 'axios'
import config from './config.js'
import { Message } from 'element-ui'
import store from '../store'

/**
 * const Axios with Interceptors
 * @param config
 * @returns {AxiosPromise}
 */
if (process.env.NODE_ENV === 'production') {
  config.baseURL = process.env.API_HOST
}
const serve = axios.create(config)

// serve.interceptors.request.use(config => {
//   let token = loginToken()
//   if (token) {
//     config.headers['Authorization'] = token
//     // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
//   }
//   return config
// }, error => {
//   Promise.reject(error)
// })

// axios respone拦截器
serve.interceptors.response.use(
  response => {
    const json = response.data
    if (!json) {
      return Promise.reject(new Error('error'))
    }
    if (response.status === 302) {
      // 302 重定向
      console.log(' interceptors.response 302')
      Message.error('抱歉，请重新登录!')
      store.dispatch('FRONT_LOGOUT').then(() => {
        location.reload() // 为了重新实例化vue-router对象 避免bug
      })
      return Promise.reject(new Error('error'))
    }
    // console.log(json)
    if (json.code) {
      const code = parseInt(json.code)
      if (code === 2 && json.msg) {
        Message.error('抱歉!' + json.msg)
      }
    }
    return json
  },
  error => {
    console.log(error)
  }
)

export default serve
